/* eslint-disable default-case */
import { message } from 'antd';
import {
  getEmpList,
  getRemarkList,
  insertRemark,
  updateEndLabor,
  updateIssFlag,
  getSendInfo,
  getLaborCont,
  signLaborCont,
  updateLabourCont,
  getEmpLaborCont,
  empLaborContChange,
  getUploadProgress,
  uploadFileSign,
  queryLaborCont,
} from '@/services/laborcontract';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'laborcontract';
const ModelAddEmp = {
  namespace,
  state: {
    activeKey: '1',
    formFieldsValue: {}, // 表单域
    expandForm: false, // 展开收起
    pageData: {
      // 列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    batchQuery: {
      // 批量上传数据
      progressPercent: 0,
    },
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/laborCont/downloadExcelErrData', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    detailList: {}, //  劳动合同详情数据
    remarkList: [],
    valuesArr: ['empName', 'cardNo', 'custId', 'tskId', 'contSignWay', 'contState'],
    tempType: null,
  },
  effects: {
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getEmpList, payload);
      const {
        pagerArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 办理备注
    *getRemark({ payload }, { call }) {
      const response = yield call(getRemarkList, payload);
      return response;
    },
    // 办理备注提交
    *remarkSubmit({ payload }, { call }) {
      const response = yield call(insertRemark, payload);
      return response;
    },
    // 终止
    updateEndLabor: [
      function*({ payload }, { call }) {
        const response = yield call(updateEndLabor, payload);
        return response;
      },
      { type: 'throttle', ms: 10000 },
    ],
    // 发放
    updateIssFlag: [
      function*({ payload }, { call }) {
        const response = yield call(updateIssFlag, payload);
        return response;
      },
      { type: 'throttle', ms: 10000 },
    ],
    // 详情接口
    *getSendInfo({ payload }, { call }) {
      const response = yield call(getSendInfo, payload);
      return response;
    },
    // 合同详情接口（新加的）
    *queryLaborCont({ payload }, { call, put }) {
      const response = yield call(queryLaborCont, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          detailList: {},
          remarkList: [],
        },
      });
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'updateModelData',
            payload: {
              detailList: response.data,
              remarkList: (response.data && response.data.responseEntryRemark) || [],
            },
          });
        } else {
          message.warning(`暂无数据!`);
        }
      } else {
        message.warning(`${response.message || '服务器端错误!'}`);
      }
      return response;
    },
    // 签订回显接口
    *getLaborCont({ payload }, { call }) {
      const response = yield call(getLaborCont, payload);
      return response;
    },
    // 签订提交数据
    signLaborCont: [
      function*({ payload }, { call }) {
        const response = yield call(signLaborCont, payload);
        return response;
      },
      { type: 'throttle', ms: 10000 },
    ],
      // 已签订修改数据
      updateLabourCont: [
        function*({ payload }, { call }) {
          const response = yield call(updateLabourCont, payload);
          return response;
        },
        { type: 'throttle', ms: 10000 },
      ],
    // 变更合同 回显数据
    *getEmpLaborCont({ payload }, { call }) {
      const response = yield call(getEmpLaborCont, payload);
      return response;
    },
    // 变更合同 提交数据
    *empLaborContChange({ payload }, { call }) {
      const response = yield call(empLaborContChange, payload);
      return response;
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress: [
      function*({ payload }, { call, put }) {
        try {
          const response = yield call(uploadFileSign, payload);
          if (response.success) {
            yield put({
              type: 'setTempType',
              payload: { tempType: response.data && response.data.tempType },
            });
            // 不是100表示需要走队列
            if (response.data && response.data.successProp !== 100) {
              const { batchId } = response.data;
              const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

              yield put.resolve({
                type: `socket/${SocketActions.subSocketChannel}`,
                payload: {
                  batchTask,
                },
              });
              // 订阅成功后再触发进度条
              yield put({
                type: 'updateModelData',
                payload: { showProgress: true },
              });
            } else {
              yield put({
                type: 'handleBatchTask',
                payload: response.data,
              });
            }
          } else {
            message.warning(response.message || '上传文件错误：服务器端错误');
          }

          // 无需返回response对象
        } catch (e) {
          console.error(e);
        }
      },
      { type: 'throttle', ms: 10000 },
    ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.laborcontract);
      const { tempType } = state;
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
          tempType,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
  },
  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置查询时保存的值
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新批量上传参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    setTempType(state, { payload }) {
      return {
        ...state,
        tempType: payload.tempType,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};

export default ModelAddEmp;
